<template>
  <div class="page-header">
    <h2 class="page-title">
      <el-icon class="title-icon"><Location /></el-icon>
      出差申请
    </h2>
    <el-button type="primary" @click="saveAsDraft">
      <el-icon><Document /></el-icon>
      保存草稿
    </el-button>
  </div>

  <!-- 申请表单 -->
  <el-card class="form-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>出差信息</span>
        <el-tag type="info">请填写完整的出差信息</el-tag>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="business-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人" prop="applicant">
              <el-input v-model="formData.applicant" placeholder="请输入申请人姓名" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input v-model="formData.department" placeholder="请输入部门名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="formData.position" placeholder="请输入职位" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 出差信息 -->
      <div class="form-section">
        <h3 class="section-title">出差信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出差类型" prop="businessType">
              <el-select
                v-model="formData.businessType"
                placeholder="请选择出差类型"
                style="width: 100%"
              >
                <el-option label="商务洽谈" value="business" />
                <el-option label="技术交流" value="technical" />
                <el-option label="培训学习" value="training" />
                <el-option label="会议参会" value="conference" />
                <el-option label="客户拜访" value="visit" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出差天数" prop="businessDays">
              <el-input-number
                v-model="formData.businessDays"
                :min="1"
                :max="30"
                :step="1"
                style="width: 100%"
                placeholder="请输入出差天数"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出发时间" prop="startTime">
              <el-date-picker
                v-model="formData.startTime"
                type="datetime"
                placeholder="选择出发时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="返回时间" prop="endTime">
              <el-date-picker
                v-model="formData.endTime"
                type="datetime"
                placeholder="选择返回时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目的地" prop="destination">
              <el-input v-model="formData.destination" placeholder="请输入出差目的地" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交通工具" prop="transportation">
              <el-select
                v-model="formData.transportation"
                placeholder="请选择交通工具"
                style="width: 100%"
              >
                <el-option label="飞机" value="plane" />
                <el-option label="高铁" value="train" />
                <el-option label="汽车" value="car" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="出差事由" prop="purpose">
              <el-input
                v-model="formData.purpose"
                type="textarea"
                :rows="4"
                placeholder="请详细说明出差事由和具体工作内容"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 费用预算 -->
      <div class="form-section">
        <h3 class="section-title">费用预算</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="交通费" prop="transportFee">
              <el-input-number
                v-model="formData.transportFee"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="交通费用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="住宿费" prop="accommodationFee">
              <el-input-number
                v-model="formData.accommodationFee"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="住宿费用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="餐饮费" prop="mealFee">
              <el-input-number
                v-model="formData.mealFee"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="餐饮费用"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="其他费用" prop="otherFee">
              <el-input-number
                v-model="formData.otherFee"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="其他费用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总费用">
              <el-input :value="totalFee" disabled style="width: 100%" placeholder="自动计算" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预算限额" prop="budgetLimit">
              <el-input-number
                v-model="formData.budgetLimit"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="预算限额"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 工作安排 -->
      <div class="form-section">
        <h3 class="section-title">工作安排</h3>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="工作交接" prop="handover">
              <el-input
                v-model="formData.handover"
                type="textarea"
                :rows="3"
                placeholder="请说明出差期间的工作交接安排"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergencyContact">
              <el-input v-model="formData.emergencyContact" placeholder="请输入紧急联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急联系电话" prop="emergencyPhone">
              <el-input v-model="formData.emergencyPhone" placeholder="请输入紧急联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 附件上传 -->
      <div class="form-section">
        <h3 class="section-title">附件上传</h3>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="相关附件">
              <el-upload
                ref="uploadRef"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :file-list="fileList"
                :on-preview="handleFilePreview"
                :on-remove="handleFileRemove"
                :before-remove="beforeFileRemove"
                :on-success="handleFileSuccess"
                :on-error="handleFileError"
                multiple
                :limit="5"
                list-type="text"
              >
                <el-button type="primary">
                  <el-icon><Upload /></el-icon>
                  点击上传
                </el-button>
                <template #tip>
                  <div class="el-upload__tip">支持jpg/png/pdf/doc/docx格式，单个文件不超过10MB</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 审批流程 -->
      <div class="form-section">
        <h3 class="section-title">审批流程</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="直接上级" prop="directManager">
              <el-select
                v-model="formData.directManager"
                placeholder="请选择直接上级"
                style="width: 100%"
              >
                <el-option label="张经理" value="zhang" />
                <el-option label="李总监" value="li" />
                <el-option label="王总" value="wang" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="财务审批" prop="financeApprover">
              <el-select
                v-model="formData.financeApprover"
                placeholder="请选择财务审批人"
                style="width: 100%"
              >
                <el-option label="陈财务" value="chen" />
                <el-option label="刘财务" value="liu" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="info" @click="saveAsDraft">保存草稿</el-button>
        <el-button type="primary" @click="submitForm">提交申请</el-button>
      </div>
    </el-form>
  </el-card>

  <!-- 出差统计 -->
  <el-card class="stats-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>出差统计</span>
      </div>
    </template>

    <el-row :gutter="20">
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon total-icon">
            <el-icon><Location /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ businessStats.total }}</div>
            <div class="stat-label">总出差次数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon days-icon">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ businessStats.days }}</div>
            <div class="stat-label">总出差天数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon cost-icon">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">¥{{ businessStats.cost }}</div>
            <div class="stat-label">总费用</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon pending-icon">
            <el-icon><Timer /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ businessStats.pending }}</div>
            <div class="stat-label">待审批</div>
          </div>
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { Location, Document, Upload, Calendar, Money, Timer } from '@element-plus/icons-vue'

// 表单引用
const formRef = ref<FormInstance>()
const uploadRef = ref()

// 表单数据
const formData = reactive({
  applicant: '张三',
  department: '技术部',
  position: '前端工程师',
  phone: '13800138000',
  businessType: '',
  businessDays: 1,
  startTime: '',
  endTime: '',
  destination: '',
  transportation: '',
  purpose: '',
  transportFee: 0,
  accommodationFee: 0,
  mealFee: 0,
  otherFee: 0,
  budgetLimit: 0,
  handover: '',
  emergencyContact: '',
  emergencyPhone: '',
  directManager: '',
  financeApprover: '',
})

// 表单验证规则
const formRules: FormRules = {
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  businessType: [{ required: true, message: '请选择出差类型', trigger: 'change' }],
  businessDays: [{ required: true, message: '请输入出差天数', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择出发时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择返回时间', trigger: 'change' }],
  destination: [{ required: true, message: '请输入出差目的地', trigger: 'blur' }],
  transportation: [{ required: true, message: '请选择交通工具', trigger: 'change' }],
  purpose: [
    { required: true, message: '请输入出差事由', trigger: 'blur' },
    { min: 10, message: '出差事由至少10个字符', trigger: 'blur' },
  ],
  handover: [{ required: true, message: '请输入工作交接安排', trigger: 'blur' }],
  emergencyContact: [{ required: true, message: '请输入紧急联系人', trigger: 'blur' }],
  emergencyPhone: [
    { required: true, message: '请输入紧急联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  directManager: [{ required: true, message: '请选择直接上级', trigger: 'change' }],
  financeApprover: [{ required: true, message: '请选择财务审批人', trigger: 'change' }],
}

// 文件上传相关
const fileList = ref<UploadUserFile[]>([])
const uploadUrl = '/api/upload'
const uploadHeaders = {
  Authorization: 'Bearer token',
}

// 出差统计
const businessStats = reactive({
  total: 12,
  days: 45,
  cost: '15,680',
  pending: 1,
})

// 计算总费用
const totalFee = computed(() => {
  return (
    formData.transportFee +
    formData.accommodationFee +
    formData.mealFee +
    formData.otherFee
  ).toFixed(2)
})

// 文件上传处理
const handleFilePreview = (file: UploadUserFile) => {
  console.log(file)
}

const handleFileRemove = (file: UploadUserFile, fileList: UploadUserFile[]) => {
  console.log(file, fileList)
}

const beforeFileRemove = (file: UploadUserFile) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`)
}

const handleFileSuccess = () => {
  ElMessage.success('文件上传成功')
}

const handleFileError = () => {
  ElMessage.error('文件上传失败')
}

// 表单操作
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  fileList.value = []
}

const saveAsDraft = () => {
  ElMessage.success('草稿保存成功')
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证返回时间是否大于出发时间
    if (formData.startTime && formData.endTime) {
      const start = new Date(formData.startTime)
      const end = new Date(formData.endTime)
      if (end <= start) {
        ElMessage.error('返回时间必须大于出发时间')
        return
      }
    }

    // 验证费用是否超出预算
    const total = parseFloat(totalFee.value)
    if (formData.budgetLimit > 0 && total > formData.budgetLimit) {
      ElMessage.warning('总费用超出预算限额，请调整费用或预算')
    }

    // 模拟提交
    ElMessage.success('出差申请提交成功')
    resetForm()
  } catch (error) {
    ElMessage.error('请检查表单信息')
  }
}

// 初始化
onMounted(() => {
  // 可以在这里加载用户信息和出差统计
})
</script>

<style scoped lang="less">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    display: flex;
    align-items: center;
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;

    .title-icon {
      margin-right: 8px;
      color: #409eff;
    }
  }
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }

  .business-form {
    .form-section {
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      .section-title {
        margin: 0 0 20px 0;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
        position: relative;
        padding-left: 12px;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 18px;
          background-color: #409eff;
          border-radius: 2px;
        }
      }
    }

    .form-actions {
      display: flex;
      justify-content: center;
      gap: 16px;
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #ebeef5;
    }
  }
}

.stats-card {
  border-radius: 8px;

  .card-header {
    font-weight: 600;
  }

  .stat-item {
    display: flex;
    align-items: center;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      font-size: 24px;
      color: white;

      &.total-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.days-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.cost-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }

      &.pending-icon {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }

    .stat-content {
      .stat-value {
        font-size: 24px;
        font-weight: 700;
        color: #303133;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .business-container {
    padding: 10px;

    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .page-title {
        font-size: 20px;
      }
    }

    .form-card {
      .business-form {
        .form-section {
          .section-title {
            font-size: 16px;
          }
        }

        .form-actions {
          flex-direction: column;
          align-items: center;
        }
      }
    }

    .stats-card {
      .stat-item {
        margin-bottom: 16px;
      }
    }
  }
}
</style>
